package com.harvey.study.data.structure.datastructure.linkedlist;

import lombok.Data;

/**
 * date: 2021-04-21 版本1
 * desc: 单向链表 头结点为第一个数据节点
 */
@Data
public class SingledLinkedList<T> {
    private int length; // 链表长度
    private Node<T> head; //链表头部节点

    public SingledLinkedList() {
        head = new Node<T>();
    }

    public boolean add(T obj,int pos){
        checkPos(pos);
        int index=0;
        Node<T> p = head;
        Node<T> q = head.next ;
        while(index++<pos){
            p = q;
            q = q.next;
        }
        p.data = obj;
        p.next = new Node<>();
        length++;    
        return true;
    }

    public boolean add(T obj){
        return add(obj,length);
    }

    public T remove(int pos){
        if(isEmpty()){
            return null;
        }
        checkPos(pos);
        int index = 0;
        Node<T> prev = head;
        while(index++ < pos-1){
            prev = prev.next;
        }
        T data = null;
        if(pos == 0){
            head = prev.next;
            data = prev.data;
        }else{
            Node<T> current = prev.next;
            data = current.data;
            prev.next = current.next;
        }
        length--;
        return data;
    }

    public T find(int pos){
        checkPos(pos);
        int index = 0;
        Node<T> p = head;
        while(index++<pos){
            p = p.next;
        }
        return p.data;
    }

    public boolean modify(T obj,int pos){

        return false;
    }

    public int size(){
        return length;
    }

    public boolean isEmpty(){
        return length==0;
    }

    public boolean clear(){
        while(length>0){
            remove(length-1);
        }
        return true;
    }


    private void checkPos(int pos){
        if(pos<0 || pos>length){
            throw new RuntimeException("参数有误");
        }
    }

    public static void main(String[] args) {
        SingledLinkedList<String> singledLinkedList = new SingledLinkedList<>();

        singledLinkedList.add("1");
        singledLinkedList.add("2");
        singledLinkedList.add("3");


        // System.out.println(singledLinkedList.remove(singledLinkedList.size()-1));
        // System.out.println(singledLinkedList.remove(singledLinkedList.size()-1));
        singledLinkedList.clear();


        Node<String> node = singledLinkedList.head;
        System.out.println(node.data);
        while(node.data!=null){
            node = node.next;
            if(node.data!=null){
                System.out.println(node.data);
            }
        }
    }
}

